import type { Module } from 'vuex'
import type { IRootState } from '../types'
import type { ILoginState } from './types'
import { LoginAccount, LoginRoleMenu, LoginUserInfo } from '@/service/api/login'
import LocalCache, { CacheKey } from '@/utils/cache'
import router from '@/router'
export const LoginModule: Module<ILoginState, IRootState> = {
  namespaced: true,
  state() {
    return {
      Token: '',
      UserInfo: '',
      RoleMenu: {}
    }
  },
  actions: {
    async AccountLoginActions({ commit, dispatch }, account) {
      const res: any = await LoginAccount({
        name: account.username,
        password: account.password
      })
      const { token, id } = res
      // 存储 Token
      if (token) {
        LocalCache.setItem(CacheKey.TOKEN, token)
        commit('setToken', token)
      }
      // 请求用户信息
      if (id) {
        dispatch('UserInfoActions', id)
      }
    },
    // 请求用户信息
    async UserInfoActions({ commit, dispatch }, id) {
      const userInfo: any = await LoginUserInfo({ id })
      // 保存用户信息
      LocalCache.setItem(CacheKey.USER_INFO, userInfo)
      commit('setUserInfo', userInfo)
      // 请求用户角色菜单
      const roleId = userInfo?.role?.id
      if (roleId) dispatch('RoleMenuActions', roleId)
    },
    // 请求用户角色菜单
    async RoleMenuActions({ commit }, roleId) {
      const roleMenu = await LoginRoleMenu({ roleId })
      // 保存用户角色菜单
      LocalCache.setItem(CacheKey.ROLE_MENU, roleMenu)
      commit('setRoleMenu', roleMenu)
      // 登录成功跳转首页
      router.push('/main')
    }
  },
  getters: {},
  mutations: {
    setToken(state, token) {
      state.Token = token
    },
    setUserInfo(state, userInfo) {
      state.UserInfo = userInfo
    },
    setRoleMenu(state, roleMenu) {
      state.RoleMenu = roleMenu
    }
  }
}
